﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace SHomeWorkshop.LunarSF.StudentInfosManager
{
    /// <summary>
    /// LocalSelecter.xaml 的交互逻辑
    /// </summary>
    public partial class LocalSelecter : UserControl
    {
        public LocalSelecter()
        {
            InitializeComponent();

            InitializeLocalInfos();
        }

        private List<AreaInfo> areaInfos = new List<AreaInfo>();

        private void AddLocalInfo(string code, string name)
        {
            areaInfos.Add(new AreaInfo(code, name));
        }

        private AreaInfo GetArea(string code)
        {
            if (string.IsNullOrEmpty(code)) return null;

            foreach (var info in areaInfos)
            {
                if (info.Code == code) return info;
            }

            return null;
        }

        private void InitializeLocalInfos()
        {
            var lines = Properties.Resources.行政区划代码表.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var line in lines)
            {
                var fields = line.Split(new char[] { ' ', ' ', '　' }, StringSplitOptions.RemoveEmptyEntries);
                if (fields.Length == 2)
                {
                    if (fields[1] != "市辖区" && fields[1] != "县" && fields[1].Contains("直辖") == false)
                    {
                        AddLocalInfo(fields[0], fields[1]);
                    }
                }
            }

            province.Items.Clear();

            int index = 1;
            foreach (var areaInfo in areaInfos)
            {
                if (areaInfo.Code.EndsWith("0000"))//省级
                {
                    province.Items.Add(new ComboBoxItem() { Content = index.ToString("D2") + "-" + areaInfo.Name, ToolTip = areaInfo.Name, Tag = areaInfo.Code, });
                    index++;
                }
            }
        }

        private void province_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var oldText = this.Text;
            city.Text = "";
            city.SelectedIndex = -1;
            city.Items.Clear();

            county.Text = "";
            county.SelectedIndex = -1;
            county.Items.Clear();

            if (province.SelectedIndex < 0) return;

            var provinceItem = province.SelectedItem as ComboBoxItem;
            var provinceCode = (provinceItem.Tag as string).Substring(0, 2);

            int index = 1;
            foreach (var areaInfo in areaInfos)
            {
                if (areaInfo.Code.StartsWith(provinceCode) && areaInfo.Code.EndsWith("0000") == false && areaInfo.Code.EndsWith("00"))//市级
                {
                    city.Items.Add(new ComboBoxItem() { Content = index.ToString("D2") + "-" + areaInfo.Name, ToolTip = areaInfo.Name, Tag = areaInfo.Code, });
                    index++;
                }
            }

            if (city.Items.Count == 0)//如果碰到直辖市，没有中间级
            {
                foreach (var areaInfo in areaInfos)
                {
                    if (areaInfo.Code.StartsWith(provinceCode) && areaInfo.Code.EndsWith("0000") == false)//直辖市的下级
                    {
                        city.Items.Add(new ComboBoxItem() { Content = index.ToString("D2") + "-" + areaInfo.Name, ToolTip = areaInfo.Name, Tag = areaInfo.Code, });
                        index++;
                    }
                }
            }

            city.IsEnabled = (city.Items.Count > 0);
            var newText = Text;
            OnPropertyChanged(new DependencyPropertyChangedEventArgs(TextProperty, oldText, newText));
            OnTextChanged(this, new TextChangedEventArgs() { OldText = oldText, NewText = newText });

            if (province.SelectedIndex == -1)
            {
                province.ToolTip = "省与直辖市、特别行政区级";
            }
            else
            {
                province.ToolTip = (province.SelectedItem as ComboBoxItem).Content as string;
            }
        }

        private void city_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var oldText = Text;
            county.Text = "";
            county.SelectedIndex = -1;
            county.Items.Clear();

            if (city.SelectedIndex < 0) return;

            var cityItem = city.SelectedItem as ComboBoxItem;
            var cityFullCode = (cityItem.Tag as string);
            if (cityFullCode.EndsWith("00") == false)
            {
                county.IsEnabled = (county.Items.Count > 0);
                //这是直辖市的下级，它没有下级了
            }
            else
            {
                var cityCode = cityFullCode.Substring(0, 4);

                int index = 1;
                foreach (var areaInfo in areaInfos)
                {
                    if (areaInfo.Code.StartsWith(cityCode) && areaInfo.Code.EndsWith("00") == false)//县级
                    {
                        county.Items.Add(new ComboBoxItem() { Content = index.ToString("D2") + "-" + areaInfo.Name, ToolTip = areaInfo.Name, Tag = areaInfo.Code, });
                        index++;
                    }
                }

                county.IsEnabled = (county.Items.Count > 0);
                if (city.SelectedIndex == -1)
                {
                    city.ToolTip = "地市级";
                }
                else
                {
                    city.ToolTip = (city.SelectedItem as ComboBoxItem).Content as string;
                }
            }

            var newText = Text;
            OnPropertyChanged(new DependencyPropertyChangedEventArgs(TextProperty, oldText, newText));
            OnTextChanged(this, new TextChangedEventArgs() { OldText = oldText, NewText = newText });
        }

        public event EventHandler<TextChangedEventArgs> TextChanged;

        public void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            if (TextChanged != null)
            {
                TextChanged(sender, e);
            }
        }

        public override string ToString()
        {
            return Text;
        }

        public string Text
        {
            get
            {
                if (this.province.SelectedIndex < 0) return "";
                if (this.city.SelectedIndex < 0) return "";

                if (this.county.SelectedIndex < 0)
                {
                    return (this.province.SelectedItem as ComboBoxItem).ToolTip.ToString() +
                        (this.city.SelectedItem as ComboBoxItem).ToolTip.ToString();
                }
                else
                {
                    return (this.province.SelectedItem as ComboBoxItem).ToolTip.ToString() +
                        (this.city.SelectedItem as ComboBoxItem).ToolTip.ToString() +
                        (this.county.SelectedItem as ComboBoxItem).ToolTip.ToString();
                }

                //return (string)GetValue(TextProperty);
            }
            set
            {
                //SetValue(TextProperty, value);
                province.Text = "";
                province.SelectedIndex = -1;

                city.Text = "";
                city.SelectedIndex = -1;

                county.Text = "";
                city.SelectedIndex = -1;

                if (string.IsNullOrEmpty(value) == false)
                {
                    foreach (ComboBoxItem item in province.Items)
                    {
                        if (value.Contains(item.ToolTip as string))
                        {
                            item.IsSelected = true;
                            break;
                        }
                    }

                    foreach (ComboBoxItem item in city.Items)
                    {
                        if (value.Contains(item.ToolTip as string))
                        {
                            item.IsSelected = true;
                            break;
                        }
                    }

                    foreach (ComboBoxItem item in county.Items)
                    {
                        if (value.Contains(item.ToolTip as string))
                        {
                            item.IsSelected = true;
                            break;
                        }
                    }
                }
            }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(LocalSelecter), new PropertyMetadata(""));


        public bool IsValicated
        {
            get
            {
                if (province.SelectedIndex < 0) return false;
                if (city.SelectedIndex < 0) return false;
                if (county.Items.Count > 0 && county.SelectedIndex < 0) return false;

                return true;
            }
        }

        private void county_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var oldText = Text;
            var newText = Text;
            OnPropertyChanged(new DependencyPropertyChangedEventArgs(TextProperty, oldText, newText));
            OnTextChanged(this, new TextChangedEventArgs() { OldText = oldText, NewText = newText });

            if (county.SelectedIndex == -1)
            {
                county.ToolTip = "县（区）级";
            }
            else
            {
                county.ToolTip = (county.SelectedItem as ComboBoxItem).Content as string;
            }
        }
    }

    class AreaInfo
    {
        public AreaInfo(string key, string values)
        {
            Code = key;
            Name = values;
        }

        public string Code { get; set; }
        public string Name { get; set; }
    }

    public class TextChangedEventArgs : EventArgs
    {
        public string OldText { get; set; }
        public string NewText { get; set; }
    }
}
